package cn.xsly.user.service.impl;

import cn.xsly.basic.constant.VerifyCodeConstant;
import cn.xsly.basic.exception.BusinessException;
import cn.xsly.basic.util.AjaxResult;
import cn.xsly.basic.util.Md5Utils;
import cn.xsly.basic.util.StrUtils;
import cn.xsly.org.domain.Employee;
import cn.xsly.org.mapper.EmployeeMapper;
import cn.xsly.user.domain.Logininfo;
import cn.xsly.user.domain.User;
import cn.xsly.user.dto.EmailDto;
import cn.xsly.user.dto.UserDto;
import cn.xsly.user.mapper.LogininfoMapper;
import cn.xsly.user.mapper.UserMapper;
import cn.xsly.user.service.IUserService;
import cn.xsly.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.Email;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void phoneRegister(UserDto dto) {
        String phone = dto.getPhone();
        String phoneCode = dto.getPhoneCode();
        String pwd = dto.getPwd();
        String confirmPwd = dto.getConfirmPwd();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(confirmPwd)) {
            throw new BusinessException("数据不能为空");
        }
        if (!pwd.equals(confirmPwd)) throw new BusinessException("两次密码不一致");
        //判断手机验证码是否过期
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone);
        if (obj == null) {
            throw new BusinessException("手机验证码已过期，请重新发送");
        }
        //判断手机验证码是否正确
        if (!obj.toString().split(":")[0].equals(phoneCode)) {
            throw new BusinessException("手机验证码错误");
        }
        //开始保存注册信息保存user和loginifo
        //dto转为userDto2User，User对象接收
        User user=userDto2User(dto);

        Logininfo logininfo=user2Loginfo(user);

        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public void emailRegister(EmailDto emailDto) throws MessagingException {
        String pwd = emailDto.getPwd();
        String email = emailDto.getEmail();
        String confirmPwd = emailDto.getConfirmPwd();
        if(StringUtils.isEmpty(pwd)||StringUtils.isEmpty(email)||StringUtils.isEmpty(confirmPwd)){
            throw new BusinessException("数据不能为空");
        }
        if (!pwd.equals(confirmPwd)) throw new BusinessException("两次密码不一致");
        User user=emailDto2User(emailDto);
        Logininfo logininfo=user2Loginfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        //设置发送方
        helper.setFrom("599271526@qq.com");
        //设置收件人
        helper.setTo(emailDto.getEmail());
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h2>店铺激活邮件<br/><a href='http://localhost:8080/shop/active/"
                +"'>点击链接激活</a></h2>",true);
        //发送邮件
        javaMailSender.send(mimeMessage);
    }

    private User emailDto2User(EmailDto emailDto) {
        User user = new User();
        BeanUtils.copyProperties(emailDto,user);
        return user;
    }

    //有了手机注册，可以不要添加了，手机注册就是添加
    @Override
    public void add(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        Logininfo logininfo = user2Loginfo(user);
        logininfoMapper.add(logininfo);
        super.add(user);
    }
    @Override
    public void delete(Long id){
        User user = userMapper.findById(id);
        logininfoMapper.delete(user.getLogininfoId());
        super.delete(id);
    }
    //需要把用户的里面的登录id也跟新进登录表里面
    @Override
    public void update(User user){
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        Long logininfoId = userMapper.findById(user.getId()).getLogininfoId();
        Logininfo logininfo = user2Loginfo(user);
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);
        super.update(user);

    }


    //把前端传的手机号传给user进行保存,同时设置颜值和密码需要连同颜值一起加密进行保存
    private User userDto2User(UserDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String byMd5 = Md5Utils.encrypByMd5(dto.getPwd()+salt);
        user.setSalt(salt);
        user.setPassword(byMd5);
        return user;
    }
    private Logininfo user2Loginfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

}
